<?php

namespace app\controller;

abstract class BaseController
{
    /**
     * 获取当前登录的用户信息
     * @return array|null
     */
    protected function getCurrentUser(): ?array
    {
        return $_SESSION['user'] ?? null;
    }

    /**
     * 获取当前登录用户的ID
     * @return int|null
     */
    protected function getCurrentUserId(): ?int
    {
        return $this->getCurrentUser()['id'] ?? null;
    }

    /**
     * 获取当前用户的未读消息
     * @return array
     */
    protected function getUnreadNotifications(): array
    {
        $currentUserId = $this->getCurrentUserId();
        if (!$currentUserId) {
            return [];
        }

        $allNotifications = $_SESSION['notifications'] ?? [];

        $unread = array_filter($allNotifications, function ($notification) use ($currentUserId) {
            return isset($notification['user_id']) && $notification['user_id'] === $currentUserId && !$notification['is_read'];
        });

        // 按时间戳倒序排列
        uasort($unread, fn($a, $b) => $b['timestamp'] - $a['timestamp']);

        return $unread;
    }

    /**
     * 渲染视图文件
     * @param string $view 视图路径 (相对于 views/ 目录)
     * @param array $data 传递给视图的数据
     */
    protected function render(string $view, array $data = []): void
    {
// ... existing code ...
        $viewFile = ROOT_PATH . 'views/' . $view . '.php';
        if (file_exists($viewFile)) {
            extract($data, EXTR_SKIP);
            require $viewFile;
        } else {
            trigger_error("View file not found: {$viewFile}", E_USER_ERROR);
        }
    }

    /**
     * 返回 JSON 响应
     * @param array $data
     * @param int $statusCode
     */
    protected function jsonResponse(array $data, int $statusCode = 200): void
    {
// ... existing code ...
        http_response_code($statusCode);
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }

    /**
     * 重定向到一个新的 URL
     * @param string $url
     */
    protected function redirect(string $url): void
    {
// ... existing code ...
        header("Location: {$url}");
        exit;
    }

    /**
     * 检查用户是否登录，如果未登录则重定向到登录页面
     */
    protected function requireLogin(): void
    {
// ... existing code ...
        if (!$this->getCurrentUser()) {
            $this->redirect('/user/login');
        }
    }
}
